package org.client.iot.ui.device.network;

import android.annotation.SuppressLint;
import android.view.View;

import com.lucky.base.network.NetworkApi;
import com.lucky.base.network.observer.BaseObserver;
import com.lucky.utils.FastjsonUtils;
import com.lucky.utils.log.LogUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.picker.widget.TimePickerView;
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder;
import com.xuexiang.xui.widget.picker.widget.listener.OnTimeSelectListener;

import org.client.iot.databinding.ActivityNetworkDataClearBinding;
import org.client.iot.databinding.ActivityNetworkDataSaveBinding;
import org.client.iot.domain.DataQuantityDto;
import org.client.iot.http.ApiService;
import org.client.iot.http.BaseDevReq;
import org.client.iot.util.TimeUtils;
import org.tzw.template.base.BaseActivity;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @Date 2025/8/20 9:32
 * @Description 离线保存
 */

public class DataSaveActivity extends BaseActivity<ActivityNetworkDataSaveBinding> {
    private MiniLoadingDialog mMiniLoadingDialog;

    @Override
    protected void initView() {
        setSupportActionBar(mRoot.toolbarDataClear.toolbarPageHead);
        mRoot.toolbarDataClear.textViewTitle.setText("离线保存");
    }

    @Override
    protected void initListener() {
        mRoot.toolbarDataClear.imgBack.setOnClickListener(v -> {
            finish();
        });
        mRoot.btnGetStartTime.setOnClickListener(v -> {
            TimePickerView mDatePicker = new TimePickerBuilder(this, (date, v12) -> mRoot.txtStartTime.setText(TimeUtils.getYearAndMonthAndDayTime(date))).setTitleText("日期选择").build();
            mDatePicker.show();
        });
        mRoot.btnGetEndTime.setOnClickListener(v -> {
            TimePickerView mDatePicker = new TimePickerBuilder(this, (date, v1) -> mRoot.txtEndTime.setText(TimeUtils.getYearAndMonthAndDayTime(date))).setTitleText("日期选择").build();
            mDatePicker.show();
        });
        mRoot.btnGetDataQuantity.setOnClickListener(v -> {
            String startDate = mRoot.txtStartTime.getText().toString();
            String endDate = mRoot.txtEndTime.getText().toString();
            if (startDate.isEmpty() || endDate.isEmpty()) {
                showToastLong("请选择开始日期和结束日期");
                return;
            }
            showLoading("查询中..");
            dataQuantity(startDate, endDate);
        });
        mRoot.btnExport.setOnClickListener(v -> {
            String startDate = mRoot.txtStartTime.getText().toString();
            String endDate = mRoot.txtEndTime.getText().toString();
            if (startDate.isEmpty() || endDate.isEmpty()) {
                showToastLong("请选择开始日期和结束日期");
                return;
            }
            String type = mRoot.spDataClearType.getSelectedItem().toString();
            if (type.isEmpty()) {
                showToastShort("请选择清空类型");
                return;
            }
            if (mRoot.txtDataQuantity.getText().toString().isEmpty()) {
                showToastShort("请先获取设备数据数量");
                return;
            }
            int dataQuantity = Integer.parseInt(mRoot.txtDataQuantity.getText().toString());
            showLoading("离线数据保存中..");
            dataSave(type, dataQuantity, startDate, endDate);

        });
    }

    //查询设备数据数量
    private void dataQuantity(String startTime, String endTime) {
        String params = FastjsonUtils.toJsonString(dataQuantityParams(startTime, endTime));
        Observable<BaseDevReq<DataQuantityDto>> compose =
                NetworkApi.createService(ApiService.class, "dev").dataQuantity
                                (RequestBody.create(MediaType.parse("application/json"), params))
                        .compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<DataQuantityDto>>() {
                            @SuppressLint({"CheckResult", "SetTextI18n"})
                            @Override
                            public void onSuccess(BaseDevReq<DataQuantityDto> req) {
                                if (req == null) {
                                    return;
                                }
                                runOnUiThread(() -> {
                                    disLoading();
                                    LogUtils.i("查询设备数据数量req==", req.toString());
                                    showToastLong(req.getMessage());
                                    if (req.getData() != null) {
                                        mRoot.txtDataQuantity.setText(req.getData().getData_quantity() + "");
                                    }
                                });

                            }

                            @SuppressLint("CheckResult")
                            @Override
                            public void onFailure(Throwable e) {
                                runOnUiThread(() -> {
                                            disLoading();
                                            showToastLong(e.getMessage());
                                        }
                                );

                            }
                        }));
    }

    //离线数据保存
    private void dataSave(String type, int dataQuantity, String startTime, String endTime) {
        String params = FastjsonUtils.toJsonString(dataClearParams(type, dataQuantity, startTime, endTime));
        Observable<BaseDevReq<Object>> compose =
                NetworkApi.createService(ApiService.class, "dev").dataSave
                                (RequestBody.create(MediaType.parse("application/json"), params))
                        .compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<Object>>() {
                            @SuppressLint({"CheckResult", "SetTextI18n"})
                            @Override
                            public void onSuccess(BaseDevReq<Object> req) {
                                if (req == null) {
                                    return;
                                }
                                runOnUiThread(() -> {
                                    disLoading();
                                    LogUtils.i("离线数据保存req==", req.toString());
                                    showToastLong(req.getMessage());

                                });

                            }

                            @SuppressLint("CheckResult")
                            @Override
                            public void onFailure(Throwable e) {
                                runOnUiThread(() -> {
                                            disLoading();
                                            showToastLong(e.getMessage());
                                        }
                                );

                            }
                        }));
    }

    private Map<String, Object> dataQuantityParams(String startTime, String endTime) {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("start_time", startTime);
        params.put("end_time", endTime);
        return params;
    }

    private Map<String, Object> dataClearParams(String type, int dataQuantity, String startTime, String endTime) {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("type", type);
        params.put("data_quantity", dataQuantity);
        params.put("start_time", startTime);
        params.put("end_time", endTime);
        return params;
    }

    private void showLoading(String msg) {
        runOnUiThread(() -> {
            mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, msg);
            mMiniLoadingDialog.show();
        });
    }

    private void disLoading() {
        runOnUiThread(() -> {
            if (mMiniLoadingDialog != null) {
                mMiniLoadingDialog.dismiss();
            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        disLoading();
    }
}
